# -*- coding: utf-8 -*-
# @Time    : 2020/3/12 16:38
# @Author  : Sunny
# @Site    : 
# @File    : modelform.py
# @Software: PyCharm
# @WeChat public address : 程序猿与python之间的秘密

from django.db import models
from django.forms import ModelForm
from django.forms import fields
from .models import User
from django import forms
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
import hashlib
from django_redis import get_redis_connection


# 自定义手机号验证是否注册功能
def checkphone(value):
    if User.objects.filter(phone=value):
        raise ValidationError('手机号已经被注册')


class UserModelForm(ModelForm):
    phone = fields.CharField(label='手机号',
                             validators=[RegexValidator(r'^(1[3|4|5|6|7|8|9])\d{9}$', '手机号格式错误'), checkphone])
    password = fields.CharField(label='密码', widget=forms.PasswordInput, min_length=6)
    confirm_password = fields.CharField(label='确认密码', widget=forms.PasswordInput, min_length=6)
    code = fields.CharField(label='验证码', min_length=4)

    class Meta:
        model = User
        fields = ['username', 'email', 'password', 'confirm_password', 'phone', 'code']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['placeholder'] = '请输入%s' % (field.label,)
            if name == 'phone':
                field.widget.attrs['id'] = 'phone'

    def clean_code(self):
        phone = self.cleaned_data.get('phone', '')
        if not phone:
            self.add_error('phone', '手机号为空')
            return ValidationError('手机号为空')
        conn = get_redis_connection()
        code = conn.get(phone).decode('utf-8')
        value = self.cleaned_data.get('code', "")
        if value == code:
            return value
        else:
            self.add_error('code', '验证码错误')
            raise ValidationError('验证码错误')

    def clean(self):
        password = self.cleaned_data.get('password', "")
        confirm_password = self.cleaned_data.get('confirm_password')
        if password == confirm_password:
            md5 = hashlib.md5()
            md5.update(password.encode('utf-8'))
            self.cleaned_data['password'] = md5.hexdigest()
            return self.cleaned_data
        self.add_error('password', '密码不一致')
        raise ValidationError('两次密码不一致')
